import {
	queryUrl
} from "@/utils/config";
import {
	login
} from "@/api/login";
const whiteList: Array<string> = ['dispatch/login'];

interface ResponseData<T = any> {
	code: number
	data: T
	msg?: string
}

interface RequestConfig {
	loading?: boolean
	method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
}

export default function http<T = any>(
	path: string,
	params: Record<string, any> = {},
	config: RequestConfig = { loading: true, method: 'GET' }
): Promise<ResponseData<T>> {
	const { loading = true, method = 'GET' } = config
	let retryCount: number = 1; //token失效，重试1次
	uni.hideLoading();
	const token = uni.getStorageSync('token');
	// if (!token) {
	// 	return Promise.reject({ code: 401, msg: '请先登录' });
	// }
	return new Promise<ResponseData<T>>((resolve, reject) => {
		// 加载 默认是true
		if (loading) {
			uni.showLoading({
				title: "加载中",
				mask: true
			}).then(r => {});
		}
		// 开始请求
		uni.request({
			header: {
				Authorization: whiteList.includes(path) ? "" : token,
				'x-source': 'dispatch',
				'Content-Type': "application/json"
			},
			url: queryUrl + path,
			method: method,
			data: params,
			async success(res) {
				uni.hideLoading();
				const data = res.data as ResponseData<T> // 类型断言
				if (data?.code === 401) {
					if (retryCount > 0) {
						uni.login({
							success: async (loginRes) => {
								const token: { wx_token?: string } = await login({  // 明确 token 类型
									"code": loginRes.code,
								})
								uni.setStorageSync("token", token?.wx_token || "");
							}
						})
						retryCount--;
					}
				}
				console.log("请求结果", data)
				uni.hideLoading();
				resolve(data);
			},
			fail(err) {
				uni.hideLoading();
				uni.showToast({
					icon: "error",
					duration: 2000,
					title: "系统异常"
				}).then(r => {});
				reject(err);
			}
		});
	});
};